import axios from 'axios'
import { Message,Loading } from 'element-ui'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.defaults.baseURL = 'https://note-server.hunger-valley.com'
axios.defaults.baseURL = '//127.0.0.1:3002'
// axios.defaults.withCredentials = true

export default function request(url, type = 'GET', data = {}) {
    return new Promise((resolve, reject) => {
      let option = {
        url,
        method: type,
        validateStatus(status) {
          return (status >=200 && status < 300) || status === 400
        }
      }
      if(type.toLowerCase() === 'get') {
        option.params = data
      }else {
        option.data = data
      }
      if(localStorage.token){
        axios.defaults.headers.common['Authorization'] = localStorage.token
      }
      let loadingInstance = Loading.service({ fullscreen: true ,background:'rgba(255,255,255,0.3)'});
      axios(option).then(res => {
        if(res.data.status === 200) {
          if(res.data.token){
            localStorage.token=res.data.token
          }
          loadingInstance.close();
          resolve(res.data)
        }else {
          loadingInstance.close();
          Message.error(res.data.msg)
          reject(res.data)
        }
      }).catch(err=>{
        loadingInstance.close();
        Message.error('网络异常')
        reject({msg: '网络异常'})
      })
    })
  }
  
  
//   request('/auth/login', 'POST', {username: 'hunger', password: '123456'})
    // .then(data=>{
    //   console.log(data)
    // })